package com.hvtt.web.utilities;

import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.UUID;

import javax.imageio.ImageIO;

/*
 * @author HVTT
 *
 */
public class ImageTest {

    private static final int IMG_WIDTH = 800;
    private static final int IMG_HEIGHT = 800;
    private static final String FILE_DESC = "D:\\SourceImg800x800EN";

    public static void transferData(File folder) throws SQLException {
        int item = 0;
//		MySqlDataAccessHelper m=new MySqlDataAccessHelper();
        Connection c = DriverManager.getConnection("jdbc:mysql://localhost/ruouminitinh.com?characterEncoding=UTF-8", "root", "danh@1987");
        PreparedStatement ps = c.prepareStatement("insert into sanpham(sanpham.SanPhamID,sanpham.HinhAnh,sanpham.SPMoi,sanpham.SPHot,sanpham.TrungBay,sanpham.ThuTu,sanpham.NgonNguID,sanpham.TenSP,sanpham.GioiThieu,sanpham.TongQuan) values (?,?,?,?,?,?,?,?,?,?);");
        try {
            File fDesc = new File(FILE_DESC);
            String[] lstFilename = folder.list();
            if (fDesc.list() != null) {
                item = fDesc.list().length;
            }

//			m.open();
            for (String filename : lstFilename) {
                String ramdom = UUID.randomUUID().toString() + Utilities.getCurrentTime().replaceAll(":", "-");
                String newFileName = ramdom + filename;

                BufferedImage originalImage = ImageIO.read(new File(folder.getPath() + File.separator + filename));
                int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
                BufferedImage resizeImageJpg = resizeImage(originalImage, type);

                ImageIO.write(resizeImageJpg, "jpg", new File(FILE_DESC + File.separator + newFileName));
//				String sql = "INSERT INTO sanpham(sanpham.SanPhamID,sanpham.NhomID,sanpham.HinhAnh,sanpham.SPMoi,sanpham.SPHot,sanpham.TrungBay,sanpham.ThuTu,sanpham.NgonNguID,sanpham.TenSP,sanpham.GioiThieu,sanpham.TongQuan,sanpham.TinhNang,sanpham.LichSu,sanpham.Download,sanpham.BangGia) " +
//						"VALUES('"+ramdom
//						+"','','"+newFileName+"',0,0,1,"+(item+1)+",'VN','Rượu "+(item+1)+"','Chưa có thông tin cho sản phẩm này...','Chưa có thông tin cho sản phẩm này...','','','','');";
//				m.executeUpdate(sql);

                ps.setString(1, ramdom);
                ps.setString(2, newFileName);
                ps.setBoolean(3, false);
                ps.setBoolean(4, false);
                ps.setBoolean(5, true);
                ps.setInt(6, (item + 1));
                ps.setString(7, "EN");
                ps.setString(8, "Wine " + (item + 1));
                ps.setString(9, "Chưa có thông tin cho sản phẩm này...");
                ps.setString(10, "Chưa có thông tin cho sản phẩm này...");
                ps.addBatch();


                item++;
                System.out.println("Resize success item " + item + " -----------");
            }
            ps.executeBatch();
            System.out.println("Execute success folder " + folder.getName() + ".......");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ps.close();
            c.close();
        }
    }

    public static void writeStrData(File folder, String desc) {
        int item = 0;
        BufferedImage image;
        try {
            File fDesc = new File(desc);
            String[] lstFilename = folder.list();
            if (fDesc.list() != null) {
                item = fDesc.list().length;
            }

            for (String filename : lstFilename) {
                image = ImageIO.read(new File(
                        folder.getPath() + File.separator + filename));
                ImageTest.writeStringToImage2(image, desc, filename, "ruouminitinh.com");

                item++;
                System.out.println("Resize success item " + item + " -----------");
            }
            System.out.println("Execute success folder " + folder.getName() + ".......");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void writeStrDataToImage(File file, String desc) {
        int item = 0;
        BufferedImage image;
        try {
            image = ImageIO.read(file);
            ImageTest.writeStringToImage2(image, desc, file.getName(), "Download");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws SQLException, IOException {
//	long start=System.currentTimeMillis();	
//	String name="C:\\Users\\Administrator\\Desktop\\RuouMiniData";
//	File fSource=new File(name);
//	String[] lstFilename=fSource.list();
//	System.out.println("Starting...");
//	for(String filename:lstFilename){
//		
//		ImageTest.transferData(new File(name+File.separator+filename));
//	}
//	System.out.println("Write success.......");
//	System.out.println("Free times : "+(start-System.currentTimeMillis())/60 +"min");
//	System.out.println("Free times(s) : "+(start-System.currentTimeMillis())%60);


//ghi chuoi den anh

        long start = System.currentTimeMillis();
        System.out.println("Starting...");
        ImageTest.writeStrDataToImage(new File("E:\\Programming\\NetBeanProgramming\\Projects\\Sources\\hvttgroup.com\\web\\images\\HVTT.png"), "D:\\source");
        System.out.println("Write success.......");
        System.out.println("Free times : " + (start - System.currentTimeMillis()) / 60 + "min");
        System.out.println("Free times(s) : " + (start - System.currentTimeMillis()) % 60);


//		BufferedImage originalImage = ImageIO.read(new File("c:\\image\\mkyong.jpg"));
//		int type = originalImage.getType() == 0? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
// 
//		BufferedImage resizeImageJpg = resizeImage(originalImage, type);
//		ImageIO.write(resizeImageJpg, "jpg", new File("c:\\image\\mkyong_jpg.jpg")); 
// 
//		BufferedImage resizeImagePng = resizeImage(originalImage, type);
//		ImageIO.write(resizeImagePng, "png", new File("c:\\image\\mkyong_png.jpg")); 
// 
//		BufferedImage resizeImageHintJpg = resizeImageWithHint(originalImage, type);
//		ImageIO.write(resizeImageHintJpg, "jpg", new File("c:\\image\\mkyong_hint_jpg.jpg")); 
// 
//		BufferedImage resizeImageHintPng = resizeImageWithHint(originalImage, type);
//		ImageIO.write(resizeImageHintPng, "png", new File("c:\\image\\mkyong_hint_png.jpg"));
    }

    private static BufferedImage resizeImage(BufferedImage originalImage, int type) {
        BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
        g.dispose();

        return resizedImage;
    }

    private static BufferedImage resizeImageWithHint(BufferedImage originalImage, int type) {

        BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
        g.dispose();
        g.setComposite(AlphaComposite.Src);

        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.setRenderingHint(RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        return resizedImage;
    }

    public static void writeStringToImage() throws IOException {
        String name = "C:\\Users\\Administrator\\Desktop\\sourceImg";
        String fileDesc = "C:\\Users\\Administrator\\Desktop\\IMG800x800";
        final BufferedImage image = ImageIO.read(new File(
                fileDesc + "\\img.jpg"));
        TextLayout textTl = new TextLayout("ruouminitinh.com", new Font("Helvetica", 1, 60), new FontRenderContext(null, false, false));

        AffineTransform textAt = new AffineTransform();
        textAt.rotate(Math.toRadians(315));
        textAt.translate(-250, image.getHeight() - 500);
        Shape shape = textTl.getOutline(textAt);
        Graphics2D g = image.createGraphics();
        g.setColor(Color.RED);


        g.draw(shape);
        g.dispose();

        ImageIO.write(image, "jpg", new File(fileDesc + "\\test1.jpg"));
    }

    public static void writeStringToImage1() throws IOException {
        String name = "C:\\Users\\Administrator\\Desktop\\sourceImg";
        String fileDesc = "C:\\Users\\Administrator\\Desktop\\IMG800x800";
        final BufferedImage image = ImageIO.read(new File(
                fileDesc + "\\img.jpg"));
        System.out.println(image.getHeight());
        TextLayout textTl = new TextLayout("ruouminitinh.com", new Font("Helvetica", 1, 60), new FontRenderContext(null, false, false));
        AffineTransform textAt = new AffineTransform();
        textAt.rotate(Math.toRadians(315));
        System.out.println(Math.toRadians(315));
        textAt.translate(-250, image.getHeight() - 400);
        Shape shape = textTl.getOutline(textAt);
        System.out.println(image.getHeight());
//	        Graphics g = image.getGraphics();
        Graphics2D gg = image.createGraphics();
        gg.setColor(Color.RED);
        gg.draw(shape);
        gg.dispose();

        ImageIO.write(image, "jpg", new File(fileDesc + "\\test2.jpg"));
    }

    public static void writeStringToImage2(BufferedImage image, String fileDesc, String filename, String data) throws IOException {
//		String fileDesc="C:\\Users\\Administrator\\Desktop\\IMG800x800";
//    	final BufferedImage image = ImageIO.read(new File(
//		        fileDesc+"\\img.jpg"));

        Graphics2D g2d = image.createGraphics();
        g2d.scale(1, 1);
        g2d.addRenderingHints(
                new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON));
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // create watermark text shape for rendering
        Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 55);
        GlyphVector fontGV = font.createGlyphVector(g2d.getFontRenderContext(), data);
        Rectangle size = fontGV.getPixelBounds(g2d.getFontRenderContext(), 0, 0);
        Shape textShape = fontGV.getOutline();
        double textWidth = size.getWidth();
        double textHeight = size.getHeight();
        AffineTransform rotate45 = AffineTransform.getRotateInstance(Math.PI / 4d);
        Shape rotatedText = rotate45.createTransformedShape(textShape);

        // use a gradient that repeats 4 times
        g2d.setPaint(new GradientPaint(0, 0,
                new Color(0f, 0f, 0f, 0.3f),
                image.getWidth() / 2, image.getHeight() / 2,
                new Color(1f, 1f, 1f, 0.3f)));
        g2d.setStroke(new BasicStroke(1.0f));

        // step in y direction is calc'ed using pythagoras + 5 pixel padding
        double yStep = Math.sqrt(textWidth * textWidth / 2) + 5;

        // step over image rendering watermark text
        for (double x = -textHeight * 3; x < image.getWidth(); x += (textHeight * 3)) {
            double y = -yStep;
            for (; y < image.getHeight(); y += yStep) {
                g2d.draw(rotatedText);
                g2d.fill(rotatedText);
                g2d.translate(10, yStep);
            }
            g2d.translate(textHeight * 3, -(y + yStep));
        }
        ImageIO.write(image, "png", new File(fileDesc + File.separator + filename));

    }
}